#!/bin/bash

scriptPath=$(dirname $0);
echo "time sync"

sqlite3 -batch -separator ' ' trace.sqlite "SELECT substr(s.logTime,1,16)-e.logTime, s.sender, s.receiver, (ds.sync NOT NULL) as senderSynced, (dr.sync NOT NULL) as receiverSynced from syncEvents as s LEFT JOIN events as e ON e.device=s.receiver and substr(e.dataobjectId,1,40)=substr(s.logTime,17,40) LEFT JOIN devices as ds ON ds.name=s.sender LEFT JOIN devices as dr ON dr.name=s.receiver WHERE e.eventName='EVENT_TYPE_DATAOBJECT_INCOMING';" > tmp-sync 

syncNodeQuery="select name from devices where sync IS NULL and type='Node' limit 1;"

syncNode=$(sqlite3 -batch trace.sqlite $syncNodeQuery)
#echo $syncNode
while [ $syncNode ]; do
 	awk -v refNodeName=$syncNode -f $scriptPath/sync2sql.awk tmp-sync > tmp-sync.sql
	sqlite3 -batch -separator ' ' trace.sqlite < tmp-sync.sql
	syncNode=$(sqlite3 -batch trace.sqlite $syncNodeQuery)
#	echo $syncNode
done

# rm tmp-sync*

